_package("caf.ui");

_import("caf.core.EventBase");
_import("caf.ui.DeckView");

/**
 * 每个视图数据可以延迟加载的视图列表
 */
_class("DeckViewList", DeckView, function(){
	var MSG_TIP = {
		"tip"     : "滑动距离超过半屏可以翻页",
		"tip_up"  : "继续滑动可以翻到上一篇文章",
		"go_up"   : "松开翻到上一篇文章",
		"is_first": "已经是第一篇文章了",
		"tip_down": "继续滑动可以翻到下一篇文章",
		"go_down" : "松开翻到下一篇文章",
		"is_last" : "已经是最后一篇文章了"
	};
	this._init = function(){
		_super._init.call(this);
		this._parentView = null;
		this._curPage = 0;  //从0开始
	};
	this.bind = function(obj, conf){
		this.setParent(conf.parent);
		this.setId(conf.id);
		this._pageSize = conf.pageSize;
		this.setItemClass(conf.itemClass);
		var page = this.getParent();
		conf.model = page._params.model._table;
		if(conf.model){
			this.setModel(conf.model, conf.key || "-" + conf.model.getPrimaryKey());  //按主键逆序排列显示
			//[TODO]如果模型中已经有数据，需要触发dataChange事件
		}
		//obj.innerHTML = "";
		this.init(obj);
	};
	this.dispose = function(){
		this._parentView = null;
		_super.dispose.apply(this);
	};
	this._insertItem = function(data, pos){
		var item = new this._itemClass();  //{ArticleView}
		var len = this._list.length;
		pos = pos || len;
		if(pos < len){
			item.__insert = this._list[pos]._self;
		}
		item.create(this, data);
		this.pushItem(item, pos);
		if(pos < len){
			delete item.__insert;
		}
		return item;
	};
	this.activeView = function(v){
		if(this._activeItem == v) return;
		if(this._activeItem){
			//this._activeItem.activate();
		}
		//v.activate();
		this._activeItem = v;
	};
	this.getCurPage = function(){
		return this._curPage;
	};
	this.setCurPage = function(v){
		this._curPage = v;
		this.dispatchEvent(new EventBase("pageChange", {"name": "curPage", "value": v}));
	};
	this.getPreviousView = function(view){
		var index = this._list.indexOf(view);
		if(index > 0){
			return this._list[index - 1];
		}
		return null;
	};
	/*
	this.getNextView = function(view){
		var index = this._list.indexOf(view);
		if(index >= this._list.length - 1){
			var v = this.createView();
		}
		return this._list[index + 1];
	};
	*/
	this.check = function(v, min, max){
		return Math.max(min, Math.min(v, max));
	};
	/**
	 * 检查当前视口在所在的视图组件
	 * 每篇文章高度都会大于滚动视口的高度
	 */
	this.checkPageNum = function(sign, offset){
		var workspace = runtime.getWorkspace();
		var n = this._curPage, ranges = [], offY = 0;
		var view = this._parentView;
		var a = -view.getOffY();
		var b = -view.getOffY() + view.getViewportH();
		var y = 0;
		ranges.push(y);
		var len = this._list.length;
		for(var i = 0; i < len; i++){
			y += this._list[i]._self.offsetHeight;  //[TODO]每个view高度在多次翻页过程中重复计算了
			ranges.push(y);
			var r0 = ranges[i];
			var r1 = ranges[i + 1];
			if(sign == 1){  //向下移动
				if(a < 0){
					workspace.showTipMsg(MSG_TIP.is_first);
					break;
				}else if(r1 < b && r1 >= a + offset[0]){  //向上翻页超过临界点
					workspace.showTipMsg(MSG_TIP.go_up);
					n = i;
					break;
				}else if(a <= r1 && r1 < a + offset[0]){  //向上翻页未到临界点
					workspace.showTipMsg(MSG_TIP.tip_up);
					n = i + 1;
					offY = -r1;
					break;
				}
			}else{  //sign == -1  //向上移动
				if(b > view._scroller.offsetHeight){
					workspace.showTipMsg(MSG_TIP.is_last);
					break;
				}else if(r1 > a && r1 <= b - offset[0]){  //向下翻页超过临界点
					workspace.showTipMsg(MSG_TIP.go_down);
					n = i + 1;
					break;
				}else if(b - offset[0] < r1 && r1 <= b){  //向下翻页未到临界点
					workspace.showTipMsg(MSG_TIP.tip_down);
					n = i;
					offY = -(r1 - view.getViewportH());
					break;
				}
			}
			//workspace.hideTip();
		}
		n = this.check(n, 0, len - 1);
		/*
		console.log("_curPage=" + this._curPage + ","
			+ "\nn=" + n + ","
			+ "\ni=" + i + ","
			+ "\na=" + a + ","
			+ "\nb=" + b + ","
			+ "\nranges=" + ranges);
		*/
		return {
			"num"   : n,
			"ranges": ranges,
			"offY"  : offY  //offset(=52px)限制之内的也需要调整到页的边界
		};
	};
	this.onScrollMove = function(ev){
		var view = this._parentView;
		var threshold = 10;
		var ds = view._moveData[view._moveData.length - 1].s - view._moveData[0].s;
		if(-threshold < ds && ds < threshold){
			return true;
		}
		this.checkPageNum(ds >= threshold ? 1 : -1, [100]);  //[52]
	};
	this.onScrollEnd = function(ev){
		var view = this._parentView;
		var threshold = 10;
		var ds = view._moveData[view._moveData.length - 1].s - view._moveData[0].s;
		if(-threshold < ds && ds < threshold){
			view.hideScrollbar();
			return true;
		}
		var info = this.checkPageNum(ds >= threshold ? 1 : -1, [100]);  //[52]
		runtime.getWorkspace().hideTip();
		if(info.num == this._curPage){
			var offY = info.offY || this.check(view.getOffY(), -view.getScrollerH() + view.getViewportH(), 0);
			if(offY != view.getOffY()){
				this.fixOffY(offY);
			}else{
				view.hideScrollbar();
			}
		}else{  //info.num != this._curPage
			var offY = -info.ranges[info.num];
			this.setCurPage(info.num);
			//this.fixOffY(offY);  //setPageNum中会自动调用fixOffY方法
			view.hideScrollbar();
		}
		return true;
	};
	this.fixOffY = function(v){
		var view = this._parentView;
		view.setOffY(v);
		if(view._top != v){
			this.animate(view._scroller, "top:" + v + "px", 200, "", this, function(){
				view.setTop(v);
				view.hideScrollbar();
			});
		}else{
			view.hideScrollbar();
		}
	};
	this.getRanges = function(){
		var ranges = [], y = 0;
		ranges.push(y);
		for(var i = 0, len = this._list.length; i < len; i++){
			y += this._list[i]._self.offsetHeight;  //[TODO]每个view高度在多次翻页过程中重复计算了
			ranges.push(y);
		}
		return ranges;
	};
	this.onPageChange = function(ev){
		if(ev.name == "curPage"){
			var n = ev.value;
			//[TODO]如果当前文章不存在，则先加载当前文章
			var data = this._list[n]._data;
			this.scrollToPage(n);
			this.getParent()._topic.id = data.topicid;
			var detail = data.__detail;
			if(!detail){
				var _this = this;
				this.getParent().preloadArticle(n, function(){
					//_this.getParent().preloadArticle(n + 1);  //不需要加载下一篇文章了
				});
			}else{
				/*
				if(!this.exist(detail.topicid)){
					var item = this._insertItem(detail);
					this.activeView(item);
				}
				if(item){
					this.activeView(item);
				}
				this.setCurPage(n);
				*/
				this.getParent().preloadArticle(n + 1);  //显示出来一片文章之后，延迟加载下一篇文章
			}
		}
	};
	this.scrollToPage = function(n){
		this.activeView(this._list[n]);
		this.fixOffY(-this.getRanges()[n]);
	};
});